package com.hzqy.web.login;

import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Field;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.springframework.util.ReflectionUtils;
import org.xml.sax.InputSource;

public class XmlUtils {
	private static final Log LOG = LogFactory.getLog(XmlUtils.class);

	/**
	 * 读取XML格式的字符串，根据属性来查找值
	 * @param xmlStr是要解析的xml格式的字符串
	 * @param name是在xml字符串中要获得标签属性
	 * @return 返回的标签属性是name的值
	 */
	public static String parseXMLStr(String xmlStr, String name) {
		String value = null;
		StringReader sr = new StringReader(xmlStr);
		InputSource is = new InputSource(sr);
		SAXBuilder sb = new SAXBuilder();
		try {
			Document d = sb.build(is);
			Element e = d.getRootElement();
			Element x = e.getChild(name);
			if (x == null) {
				return null;
			} else {
				value = x.getValue();
			}
		} catch (JDOMException e) {
			LOG.error("读取XML格式的字符串，根据属性来查找值出错：", e);
		} catch (IOException e) {
			LOG.error("读取XML格式的字符串，根据属性来查找值出错：", e);
		}
		return value;
	}

	/**
	 * 将XML属性值写入传入的对象内对应的属性
	 *
	 * @param object
	 * @param xmlStr
	 * @param level 根目录下的第一个级别为0
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws IOException
	 * @throws JDOMException
	 */
	public static void writeObject(Object object, String xmlStr,int level)throws IllegalArgumentException, IllegalAccessException,JDOMException, IOException {
		StringReader sr = new StringReader(xmlStr);
		InputSource is = new InputSource(sr);
		SAXBuilder sb = new SAXBuilder();
		Document d = sb.build(is);
		Element e = d.getRootElement();
		if(level>0){
			for(int i=0;i<level;i++){
				e = (Element)e.getChildren().get(0);
			}
		}
		Field[] fields = object.getClass().getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			String varName = fields[i].getName();
			boolean accessFlag = fields[i].isAccessible();
			//fields[i].setAccessible(true);
			ReflectionUtils.makeAccessible(fields[i]);
			Element x = e.getChild(varName);
			if (x != null && x.getValue().length() > 0) {
				String value = x.getValue();
				fields[i].set(object, value);
			}
			//fields[i].setAccessible(accessFlag);
			/*if(!accessFlag){
				fields[i].setAccessible(false);
			}*/

		}
	}

	public static void main(String args[]) throws Exception {
	}
}
